<?php

namespace app\api\controller;

//新闻的基类
use think\Config;
use think\Db;
use think\Exception;

class NewsBase
{

    //mongo对象
    public $mongo_obj;
    public static $user_type;

    public function __construct()
    {
        try {

            //上线后隐去
            //$_SERVER['HTTP_USERTOKEN'] = Config::get('HTTP_USERTOKEN');

            //$_SERVER['HTTP_DEVICETOKEN'] = '最新测试device_token';

            if (isset($_SERVER['HTTP_USERTOKEN'])) {
                //判断当前用户是不是正常
                //$user_id = Db::name('user')->where()->value('user_id');
                $user_token = $_SERVER['HTTP_USERTOKEN'];

                $arr = verification($user_token);

                //获取到的user_id
                $user_id = $arr['user_data']->user_id;

                //获取当前用户的
                $user_info = Db::name('user')->where(['user_id' => $user_id])->field('user_id,device_token_md5,user_unique,nick_name,head_img')->find();

                //登录用户
                self::$user_type = 'login';

            } elseif (isset($_SERVER['HTTP_DEVICETOKEN'])) {
                //判断当前设备的用户是不是正常
                $device_token = $_SERVER['HTTP_DEVICETOKEN'];

                //获取当前用户的
                $user_info = Db::name('user')->where(['device_token' => $device_token, 'user_type' => 0])->field('user_id,device_token_md5,user_unique')->find();

                if(!$user_info){

                    //当前不存在，使用device_token
                    //echo '当前device_token不存在,创建新的';

                    $login = new Login();

                    $user_id = $login->uploadingDeviceToken($device_token);

                    //获取当前用户的
                    $user_info = Db::name('user')->where(['user_id' => $user_id])->field('user_id,device_token_md5,user_unique')->find();

                }

                //游客
                self::$user_type = 'not_login';

            } else {
                throw new Exception('devicetoken与usertoken不存在于header中');
            }

            if ($user_info) {

                switch (self::$user_type) {
                    case 'login':
                        $this->nick_name = $user_info['nick_name'];
                        $this->head_img = $user_info['head_img'];
                        break;
                    case 'not_login':
                        $this->nick_name = '';
                        $this->head_img = '';
                        break;
                }

                $this->user_id = $user_info['user_id'];
                $this->user_unique = $user_info['user_unique'];
                $this->imei = $user_info['device_token_md5'];
                $this->mongo_obj = Db::connect("db_mongo");
            } else {
                throw new Exception('用户信息不存在');
            }

        } catch (\Exception $exception) {
            errorBack($exception);
        }
    }
}